package com.qiche.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.qiche.model.Card;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.google.gson.Gson;

/**
 * HttpYtils : http请求工具类
 *
 * @author zhangds
 * @since 2017-04-19 12:14
 */
public class HttpUtils {

	/**
	 * 发送post请求 请求体默认为application/json
	 * 
	 * @param requestUrl
	 *            请求url
	 * @param para
	 *            请求参数 json格式的字符串
	 * @return
	 * @throws IOException
	 */
	public static String sendPost(String requestUrl, String para) {

		String result = "";
		try {
			StringEntity paraEntity = new StringEntity(para, "utf-8");// 解决中文乱码问题
			paraEntity.setContentEncoding("UTF-8");
			paraEntity.setContentType("application/json");

			CloseableHttpClient client = HttpClients.createDefault();
			HttpPost httpPost = new HttpPost(requestUrl.toString());
			httpPost.setEntity(paraEntity);
			CloseableHttpResponse response = client.execute(httpPost);
			try {
				HttpEntity entity = response.getEntity();
				result = EntityUtils.toString(entity);
			} finally {
				response.close();
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return result;
	}

	/**
	 * 发送get请求
	 * 
	 * @param requestUrl
	 *            请求URL
	 * @return
	 * @throws IOException
	 */
	public static String sendGet(String requestUrl) {

		String result = "";
		try {

			CloseableHttpClient client = HttpClients.createDefault();
			HttpGet httpGet = new HttpGet(requestUrl.toString());
			CloseableHttpResponse response = client.execute(httpGet);
			try {
				HttpEntity entity = response.getEntity();
				result = EntityUtils.toString(entity);
			} finally {
				response.close();
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 向指定URL发送GET方法的请求
	 *
	 * @param url
	 *            发送请求的URL
	 * @param param
	 *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return URL 所代表远程资源的响应结果
	 */
	public static String sendGet(String url, String param) {
		String result = "";
		BufferedReader in = null;
		try {
			String urlNameString = url + "?" + param;
			URL realUrl = new URL(urlNameString);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			connection.setRequestProperty("Accept-Charset", "utf-8");
			connection.setRequestProperty("contentType", "utf-8");
			// 建立实际的连接
			connection.connect();
			// 获取所有响应头字段
			Map<String, List<String>> map = connection.getHeaderFields();

			// 定义 BufferedReader输入流来读取URL的响应

			in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));

			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送GET请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return result;
	}

	public static void main(String[] args) throws Exception {

		Gson gson = new Gson();
		/*
		 * String result = sendGet(
		 * "http://120.77.36.82:8080/rest/geetest/cracker?targetUrl=http%3A%2F%2Fantirobot.tianyancha.com%2Fcaptcha%2FgetGtCaptcha%3Ft%3D%25s&userId=000000005b3d57ea015b3d796a9f0f8f"
		 * ); JsonObject jsonObject = gson.fromJson(result,JsonObject.class);
		 * 
		 * String geetest_challenge =
		 * jsonObject.get("data").getAsJsonObject().get("geetest_challenge").getAsString
		 * (); String geetest_validate =
		 * jsonObject.get("data").getAsJsonObject().get("geetest_validate").getAsString(
		 * ); String geetest_seccode =
		 * URLEncoder.encode(jsonObject.get("data").getAsJsonObject().get(
		 * "geetest_seccode").getAsString()).replace("%7C","%7c");
		 * 
		 * String tyurl =
		 * "http://www.tianyancha.com/cd/ver/13627691572/SMS.json?geetest_challenge="+
		 * geetest_challenge+"&geetest_validate="+geetest_validate+"&geetest_seccode="+
		 * geetest_seccode+"&funtype=1";
		 * 
		 * System.out.println(tyurl); String res = sendGet(tyurl);
		 * System.out.println(res);
		 * 
		 * 
		 */
		List<Card> cards = new ArrayList<>();
		Card card = new Card();
		card.setCardTitle("gg");
		card.setCardType("www");
		cards.add(card);

		Card card2 = new Card();
		card2.setCardTitle("gg3");
		card2.setCardType("www3");
		cards.add(card2);
		// String data=gson.toJson(cards);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("json", cards);

		DesUtils des = new DesUtils("YHL_ojbk");
		String token = des.encrypt("dxfq");
		map.put("token", token);
		System.out.println(gson.toJson(map));

		sendPost("http://localhost:8080/rest/yhl/postCard", gson.toJson(map));

	}

}
